<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\Responder;
use \StudyBuddy\Validate;
use \StudyBuddy\Captcha;
use \StudyBuddy\String;

/**
 * Class for processing registration
 * form which is ONLY sent
 * via AJAX and is presented in modal DIALOG
 * window
 *
 */
class Quickreg extends Join
{

	protected $aAllowedVars = array(
    								'tzo',
                                    'email',
                                    'username',                                  
    								 'public_key',
    							     'hncaptcha',
    								 'terms',
    								 'submit',
                                     'private_key');


	protected $aRequired = array('username', 'email');

	/**
	 * Registered members are not allowed to use this
	 * method
	 *
	 * @var string
	 */
	protected $permission = 'register';

	public function main(){
		/**
		 * $this->username and $this->pwd
		 * are used in createNewUser() in Register
		 */
		$this->username = $this->oRequest['username'];
		$this->pwd = String::makePasswd();

		$this->validateCaptcha()
		->checkUsername()
		->validateEmail()
		->createNewUser()
		->createEmailRecord()
		->sendActivationEmail()
		->setReturn();
	}


	/**
	 *
	 */
	protected function validateCaptcha(){
		if(!empty($_SESSION['reg_captcha'])){
			return $this;
		}

		$oCaptcha = Captcha::factory($this->oRegistry);
		$res = $oCaptcha->validate_submit();
		/**
		 * If validation good then
		 * all is OK
		 */
		if(1 === $res){
			$_SESSION['reg_captcha'] = true;

			return $this;
		}

		/**
		 * If 3 then reached the limit of attampts
		 */
		if(3 === $res){
			throw new \StudyBuddy\CaptchaLimitException('You have reached the limit of image verification attempts');
		}

		$aRet = array(
		'exception' => 'Incorrect image verification text<br/>Please try again',
		'fields' => array('private_key'),
		'captcha' => $oCaptcha->getCaptchaArray());

		Responder::sendJSON($aRet);

	}

}
